package com.fuxi.cloud.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * ViewFreemarker
 *
 * @Author: 扫地僧
 * @CreateTime: 2021-05-03
 */
public class ViewFreemarker implements InitializingBean {
    static final Logger logger = LoggerFactory.getLogger(ViewFreemarker.class);
    private static Configuration _tplConfig = new Configuration();

    public ViewFreemarker() {
    }

    private static String parseTemplate(String tplName, String encoding, Map<String, Object> paras) {
        try {
            StringWriter var3 = new StringWriter();
            Template var4 = null;
            var4 = _tplConfig.getTemplate(tplName, encoding);
            var4.process(paras, var3);
            return var3.toString();
        } catch (Exception var5) {
            var5.printStackTrace();
            return var5.toString();
        }
    }

    public static void view(HttpServletRequest request, HttpServletResponse response, String template, Map<String, Object> paras) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("Freemarker loading：" + template);
        }

        if (paras == null) {
            paras = new HashMap();
        }

        ((Map)paras).put("request", request);
        ((Map)paras).put("response", response);
        String var4 = parseTemplate(template, "UTF-8", (Map)paras);
        outputToPage(request, response, var4);
    }

    private static void outputToPage(HttpServletRequest request, HttpServletResponse response, String content) throws Exception {
        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter var3 = null;

        try {
            if (!response.isCommitted()) {
                var3 = response.getWriter();
                var3.println(content);
                var3.flush();
                var3.close();
            }
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            try {
                if (var3 != null) {
                    var3.close();
                }
            } catch (Exception var12) {
                ;
            }

        }

    }

    public void afterPropertiesSet() throws Exception {
    }

    static {
        _tplConfig.setClassForTemplateLoading(ViewFreemarker.class, "/templates");
        _tplConfig.setDefaultEncoding("UTF-8");
    }
}
